from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt

from login_api.models import User
from util import captcha
from util.request_util import post_only, login_only
from util.response import LoginResponse, RegistryResponse


@csrf_exempt
@post_only
def login_api(request):
    """
    登录接口
    """
    session = request.session

    captcha_str: str = request.POST.get("code", '')
    session_captcha_str: str = session.get("captcha_str")

    session["captcha_str"] = ""

    if not session_captcha_str or captcha_str != session_captcha_str:
        return LoginResponse.CAPTCHA_ERROR

    try:
        user = User.objects.get(username=request.POST.get("account"))
    except User.DoesNotExist:
        return LoginResponse.ACCOUNT_NOT_FOUND

    if user.password != request.POST.get("password"):
        return LoginResponse.PASSWORD_ERROR

    # 登录成功后在cookies里保存token
    token: str = captcha.gen_random_str(50)
    user.token = token
    user.save()

    session["login"] = True
    session["id"] = user.id

    response = JsonResponse({"state": 1, "message": "登录成功"})
    response.set_cookie("token", token)
    response.set_cookie("id", user.id)

    return response

@csrf_exempt
@post_only
def registry_api(request):
    """
    注册接口
    """
    session = request.session

    captcha_str: str = request.POST.get("code", '')
    session_captcha_str: str = session.get("captcha_str")

    if not session_captcha_str or captcha_str != session_captcha_str:
        session["captcha_str"] = ""
        return RegistryResponse.CAPTCHA_ERROR

    username = request.POST.get("account")
    user = User.objects.filter(username=username).first()

    if user:
        return RegistryResponse.USERNAME_EXIST

    try:
        User.objects.create(username=username, password=request.POST.get("password"), auth=User.AuthLevel.NORMAL)
    except Exception as e:
        print(e)
        return RegistryResponse.SERVER_ERROR

    return RegistryResponse.SUCCESS_REGISTRY


def login_captcha_api(request):
    """
    验证码接口
    """
    captcha_str = captcha.gen_random_str(4)
    request.session['captcha_str'] = captcha_str
    return HttpResponse(f"data:image/png;base64,{captcha.gen_captcha_img_base64(captcha_str)}")


@csrf_exempt
@post_only
@login_only
def user_info_api(request):
    """
    个人信息接口
    """
    session = request.session
    user_id = session.get("id")
    user = User.objects.get(id=user_id)
    if user:
        return JsonResponse({'state': 1, 'info': user.to_dict()})
    return JsonResponse({'state': -1, 'info': {}})
